/**
 * Created by seth.yang on 2016/9/13
 */
if (!window.dw) {
    var dw = (function ($) {
        var panels = [];

        function closeAllPanel () {
            $(panels).each (function (i, p) {
                $(p).hide ();
            });
        }

        function showAjaxError (e, response) {

        }

        $(document).on ('click', closeAllPanel);

        return {
            escapeHTML : function (text) {
                return text.replace (/([\s\n<>&])/g, function (w, m) {
                    switch (m) {
                        case '\n' : return '<br />\n';
                        case ' ' : return '&nbsp;';
                        case '<' : return '&lt;';
                        case '>' : return '&gt;';
                        case '&' : return '&amp;';
                        default : return m;
                    }
                });
            },
            create : function (tagName, id, className, parent) {
                var e = document.createElement (tagName);
                if (id) e.id = id;
                if (className) e.className = className;
                if (parent && parent.appendChild)
                    parent.appendChild (e);
                return e;
            },
            call : function (target, args) {
                if (!args) return;
                target = target || window;

                var callable = args [args.length - 1],
                    params = Array.prototype.slice.call (args, 0, -1);
                if (callable)
                    callable.apply (target, params);
            },
            pushPanel : function (panel) {
                panels.push (panel);
                $(panel).on ('click', function (e) {
                    e.stopPropagation ();
                });
                return panel;
            },
            setPosition: function (sender, target, options) {
                var h = sender.height ();
                var w = sender[0].clientWidth;
                var x = sender.offset ().left;
                var y = sender.offset ().top + h + 6;
                var height = target.scrollHeight;

                var HEIGHT = window.outerHeight;
                var scrollY = window.scrollY || window.pageYOffset;
                var upper = y - scrollY;
                var bottom = HEIGHT - upper;

                if (bottom < height && upper > height) {
                    y -= h + height + 10;
                }
                var css = {left:x, top:y};
                if (options && !options ['ignoreWidth']) {
                    css.width = w;
                }
                $(target).css (css);
            },
            closeAllPanel : closeAllPanel,
            Browser : (function (ua) {
                var ie = /^Mozilla\/.*?\(compatible; MSIE ([\d\.]+);\sWindows( NT )?\s*([\d\.]+)(;(\sWOW64;)?.*?\sTrident\/([\d\.]+).*)?\)$/;
                var opera = /^Opera\/.*?Presto\/([\d\.]+)\sVersion\/([\d\.]+).*$/;
                var firefox = /^Mozilla\/.*?Gecko\/([\d]+).*?Firefox\/([\d\.]+).*$/;
                var chrome = /^Mozilla\/.*?\(.*?AppleWebKit\/([\d\.\+]+)\s*\(KHTML, like Gecko\).*?Chrome\/([\d\.]+).*?Safari\/([\d\.]+).*$/;
                var android = /^Mozilla\/.*?\(Linux; U; Android.*?AppleWebKit\/([\d\.\+]+)\s*\(KHTML, like Gecko\).*?(Version\/([\d\.]+))? Mobile Safari\/[\d\.]+.*?/i;
                var iphone = /^Mozilla\/.*?\((iPhone|iPad).*?AppleWebKit\/([\d\.]+)\s*\(KHTML, like Gecko\).*?Version\/([\d\.]+) Mobile\/.*?Safari\/[\d\.]+.*?/i;
                var safari = /^Mozilla\/.*?AppleWebKit\/([\d\.]+)\s*\(KHTML, like Gecko\).*?Version\/([\d\.]+).*?Safari\/[\d\.]+.*?$/i;

                var patterns = [
                    {name:'opera', pattern:opera}, {name:'firefox', pattern:firefox},
                    {name:'chrome', pattern:chrome}, {name:'safari', pattern:safari}
                ];
                var value = {};
                if (ie.test (ua)) {
                    value.type = 'ie';
                    value.isIe = true;
                    value.version = parseFloat (RegExp.$1);
                } else {
                    for (var i = 0; i < patterns.length; i ++) {
                        if (patterns [i].pattern.test (ua)) {
                            value.type = patterns [i].name;
                            break;
                        }
                    }
                }

                if (value.isIe) {
                    value ['isIe' + value.version] = true;
                }
                if (ua.indexOf('MetaSr') >= 0) {
                    value.metasr = true;
                }
                return value;
            })(window.navigator.userAgent),
            ajax : function (parameter, success, error) {
                error = error || showAjaxError;
                $.ajax (parameter).success (function (response) {
                    var ret = eval ('(' + response + ')');
                    if (ret) {
                        switch (ret ['status']) {
                            case 'ok' :
                                success (ret ['data']);
                                break;
                            case 'fail':
                                alert (ret ['cause']);
                                break;
                            case 'ajax-expired':
                            {
                                var login_page = ret ['login-page'];
                                location.assign (login_page);
                            }
                        }
                    }
/*
                    if (ret && ret ['status'] == 'ok') {
                        success (ret ['data']);
                    } else {
                        alert (ret ['cause']);
                    }
*/
                }).error (error);
            },
            support : (function () {
                var div = document.createElement("div");

                div.style.display = "none";
                div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';
                var a = div.getElementsByTagName("a")[0];
                return {
                    // IE strips leading whitespace when .innerHTML is used
                    leadingWhitespace: div.firstChild.nodeType == 3,

                    // Make sure that tbody elements aren't automatically inserted
                    // IE will insert them into empty tables
                    tbody: !div.getElementsByTagName("tbody").length,

                    // Make sure that you can get all elements in an <object> element
                    // IE 7 always returns no results
                    objectAll: !!div.getElementsByTagName("object")[0].getElementsByTagName("*").length,

                    // Make sure that link elements get serialized correctly by innerHTML
                    // This requires a wrapper element in IE
                    htmlSerialize: !!div.getElementsByTagName("link").length,

                    // Get the style information from getAttribute
                    // (IE uses .cssText insted)
                    style: /red/.test( a.getAttribute("style") )
                };
            })()


    };
    })(jQuery),
    dreamwork = dw;
}

if (!window.call) var call = function (target, args) {
    if (!args) return;
    target = target || window;

    var callable = args [args.length - 1],
        params = Array.prototype.slice.call (args, 0, -1);
    if (callable)
        callable.apply (target, params);
};

if (!window.invoke) var invoke = function () {
    var target = Array.prototype.shift.call (arguments),
        callable = Array.prototype.shift.call (arguments),
        params = Array.prototype.slice.call (arguments, 0);
    if (!callable)
        throw 'Invalid parameter: callback must be set!';
    target = target || window;
    if (callable)
        return callable.apply (target, params);
    return null;
};

if (!window.Reflector) var Reflector = {
    toXMLString : function (o, tagName) {
        var rootName = tagName || 'reflect-object';
        var s = '';
        if (o instanceof Array) {
            if (!tagName) s += '<list>';
            for (var i = 0; i < o.length; i ++) {
                s += Reflector.toXMLString (o[i], rootName);
            }
            if (!tagName) s += '</list>';
            return s;
        }
        s = '<' + rootName + '>';
        if (o instanceof String || typeof o == 'string')
            s += '<![CDATA[' + Reflector.__xmlEncode (o) + ']]>';
        else if (o instanceof Number || typeof o == 'number') {
            s += o;
        } else if (o instanceof Date) {
            s += o.formatTime ();
        } else {
            for (var k in o) {
                if (o.hasOwnProperty(k)) {
                    var v = o [k];
                    if (typeof v != 'function') s += Reflector.toXMLString (v, k);
                }
            }
        }
        s += '</' + rootName + '>';
        return s;
    },
    toJsonString : function (o) {
        if (o instanceof Array)
            return Reflector.arrayToString (o);
        if (o instanceof Date || typeof o == 'date')
            return Reflector.formatDate(o);
        if (o instanceof Number || typeof o == 'number')
            return o;
        if (o instanceof String || typeof o == 'string')
            return '"' + o.replace (/"/g, '\\"') + '"';
        if (o instanceof Boolean || typeof o == 'boolean')
            return o;

        var s = '', k, v;
        for (k in o) {
            if (o.hasOwnProperty(k)) {
                v = o[k];
                if (s.length > 0) s += ',';
                if (typeof v != 'function') {
                    s += '"' + k + '":' + Reflector.toJsonString(v);
                }
            }
        }
        return '{' + s + '}';
    },
    arrayToString : function  (a) {
        var s = '';
        for (var i = 0; i < a.length; i ++) {
            if (s.length > 0) s += ',';
            s += Reflector.toJsonString(a [i]);
        }
        return '[' + s + ']';
    },
    formatDate : function  (a) {
        var year = a.getFullYear ();
        var month = a.getMonth () + 1;
        var date = a.getDate ();

        var s = year + '-';
        if (month < 10) s += '0';
        s += month + '-';
        if (date < 10) s += '0';
        return "'" + s + date + "'";
    },
    __xmlEncode : function  (text) {
        return  text.replace ('&', '&amp;').replace ('<', '&lt;').replace ('>', '&lt;');
    }
};

if (!window.resizeImage) var resizeImage = function (container, image) {
    var cw = container.width (), ch = container.height (),
        iw = image.width, ih = image.height;
    var scale_x = cw / iw, scale_y = ch / ih;
    if (scale_x < 1 || scale_y < 1) {
        var scale = Math.min (scale_x, scale_y);
        var w = scale * image.width, h = scale * image.height;
        $(image).css ({
            width:w, height:h,
            top:(ch - h) / 2
        });
    }
};

if (!String.trim) String.trim = function () {
    return this.replace (/^\s+|\s+$/ig, '');
};

let TextFormatter = (function () {
    function str_repeat(i, m) {
        let o = [];
        while (m > 0)
            o [--m] = i;
        return o.join('');
    }

    return {
        sprintf : function () {
            let i = 0, a, f = arguments[i++], o = [], m, p, c, x, s = '', L;
            while (f) {
                if ((m = /^[^\x25]+/.exec(f))) {
                    o.push(m[0]);
                }
                else if ((m = /^\x25{2}/.exec(f))) {
                    o.push('%');
                }
                else if ((m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f))) {
                    if (((a = arguments[m[1] || i++]) === null) || (a === undefined)) {
                        throw('Too few arguments.');
                    }
                    if (/[^s]/.test(m[7]) && (typeof(a) != 'number')) {
                        throw('Expecting number but found ' + typeof(a));
                    }
                    L = m[6] ? parseInt (m[6]) : 0;
                    switch (m[7]) {
                        case 'b': a = a.toString(2); break;
                        case 'c': a = String.fromCharCode(a); break;
                        case 'd': a = parseInt(a); break;
                        case 'e': a = m[6] ? a.toExponential(L) : a.toExponential(); break;
                        case 'f': a = m[6] ? parseFloat(a).toFixed(L) : parseFloat(a); break;
                        case 'o': a = a.toString(8); break;
                        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, L) : a); break;
                        case 'u': a = Math.abs(a); break;
                        case 'x': a = a.toString(16); break;
                        case 'X': a = a.toString(16).toUpperCase(); break;
                    }
                    a = (/[def]/.test(m[7]) && m[2] && a >= 0 ? '+'+ a : a);
                    c = m[3] ? m[3] === '0' ? '0' : m[3].charAt(1) : ' ';
                    x = m[5] - String(a).length - s.length;
                    p = m[5] ? str_repeat(c, x) : '';
                    o.push(s + (m[4] ? a + p : p + a));
                }
                else {
                    throw('unsupported pattern');
                }
                f = f.substring(m[0].length);
            }
            return o.join('');
        },
        format: (n, d, g) => {
            if (n === undefined || n === null) return '';
            if ((typeof n !== 'number') || Math.abs (n) < 1000) return n;
            let sign = n < 0 ? '-': '';
            n = Math.abs (n);

            if (typeof d === 'number') {
                g = d;
                d = ',';
            } else if (d === null || d === undefined) {
                d = ',';
            } else {
                d = d.toString ()[0];
            }
            if (isNaN (g)) {
                g = 3;
            }

            let a = [], s = n.toString(), m, p = s.indexOf ('.'), t;
            if (p >= 0) {
                t = s.substring (p + 1);
                s = s.substring (0, p);
            }
            m = s.length;
            for (let i = 0; i < m; i ++) {
                if (i > 0 && (i % g === 0)) {
                    a.push (d);
                }
                a.push (s[m - i - 1]);
            }
            return sign + a.reverse ().join ('') + (t ? '.' + t : '');
        }
    };
})();

if (!('sprintf' in window)) {
    window.sprintf = TextFormatter.sprintf;
}